package com.why.blog.common.utils;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * description: 时间戳
 *
 * @author: taohan
 * @date: 2019年03月27日
 * @time: 16:58
 */
public class TimestampUtil {

	/**
	 * 获取当前日期 时间戳
	 * @return
	 */
	public static Long currentTimeStamp() {
		return new Date().getTime();
	}

	/**
	 * 获取指定日期时间戳
	 * format: yyyy-MM-dd HH:mm:ss
	 * @param dateTime 2018-03-27 17:10:50
	 * @return
	 */
	public static Long dateTime2timeStamp(String dateTime) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		return Date.from(LocalDateTime.parse(dateTime, formatter).atZone(ZoneId.systemDefault()).toInstant()).getTime();
	}

	/**
	 * 年月日转换为时间戳
	 * format: yyyy-MM-dd
	 * @param dateTime 2018-04-09
	 * @return
	 */
	public static Long YYYY_MM_DD2timeStamp(String dateTime) {
		LocalDate localDate = LocalDate.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

		return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()).getTime();
	}

	/**
	 * 年月日小时转换为时间戳
	 * format: yyyy-MM-dd HH
	 * @param dateTime 2018-04-09 08
	 * @return
	 */
	public static Long YYYY_MM_DD_HH2timeStamp(String dateTime) {
		LocalDateTime localDateTime = LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH"));
		return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()).getTime();
	}

	/**
	 * 时间戳转换为日期
	 * return date format: yyyy-MM-dd HH:mm:ss
	 * @param timeStamp 时间戳
	 * @return
	 */
	public static String timeStamp2DateTime(Long timeStamp) {
		if (timeStamp == null) {
			//throw new NullPointerException();
			return  null;
		}
		Instant instant = Instant.ofEpochMilli(timeStamp);
		//Instant instant = Instant.ofEpochSecond(timeStamp);
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
		
		return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
	}

	/**
	 * 在给定日期时间基础上减少指定小时数, 并返回时间戳
	 * @param dateTime 日期基础
	 * @param minusHour 减少小时数
	 * @return
	 */
	public static Long dateTimeMinusHours2TimeStamp(String dateTime, Integer minusHour) {
		String minusDateTime = DateTime.parse(dateTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).minusHours(minusHour).toString("yyyy-MM-dd HH");
		
		return YYYY_MM_DD_HH2timeStamp(minusDateTime);
	}

	/**
	 * LocalDateTime 日期对象转时间戳
	 * @param dateTime LocalDateTime Object
	 * @return
	 */
	public static Long localDateTime2TimeStamp(LocalDateTime dateTime) {
		return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant()).getTime();
	}

	public static void main(String[] args) throws Exception {
		System.out.println(timeStamp2DateTime(1556848800000L));
		System.out.println(timeStamp2DateTime(1556841600000L));
	}
}
